#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time   : 2021/7/12 20:36
# @Author : cjw
from typing import List

from fastapi.templating import Jinja2Templates
from fastapi import APIRouter, Depends, HTTPException, status, Request
from sqlalchemy.orm import Session
from coronavirus import crud, schemas
from coronavirus.database import engine, Base, SessionLocal
from coronavirus.models import City, Data

application = APIRouter()
templates = Jinja2Templates(directory='./coronavirus/templates')

# 生成数据库
Base.metadata.create_all(bind=engine)


def get_db():
	"""数据库连接"""
	db = SessionLocal()
	try:
		yield db
	finally:
		db.close()


@application.post('/create_city', response_model=schemas.ReadCity, summary='创建城市')
async def create_city(city: schemas.CreateCity, db: Session = Depends(get_db)):
	"""
	创建城市
	- **city**: 创建城市的数据
	- **db**: 依赖注入的数据库连接
	"""
	db_city = crud.get_city_by_name(db, city.province)
	if db_city:
		raise HTTPException(
			status_code=status.HTTP_400_BAD_REQUEST,
			detail=f'{city.province} 信息已存在！'
		)
	return crud.create_city(db, city)


@application.get('/get_city_by_name/{city_name}', response_model=schemas.ReadCity, summary='根据城市名称查询城市信息')
async def get_city_by_name(city_name: str, db: Session = Depends(get_db)):
	"""
	根据城市名称查询城市信息
	- **city_name**: 城市名称
	- **db**: 依赖注入的数据库连接
	"""
	db_city = crud.get_city_by_name(db, city_name)
	if not db_city:
		raise HTTPException(
			status_code=status.HTTP_404_NOT_FOUND,
			detail=f'{city_name} 信息不存在！'
		)
	return db_city


@application.get('/get_city_by_id/{city_id}', response_model=schemas.ReadCity, summary='根据城市ID查询城市信息')
async def get_city_by_id(city_id: int, db: Session = Depends(get_db)):
	"""
	根据城市ID查询城市信息
	- **city_id**: 城市ID
	- **db**: 依赖注入的数据库连接
	"""
	db_city = crud.get_city(db, city_id)
	if not db_city:
		raise HTTPException(
			status_code=status.HTTP_404_NOT_FOUND,
			detail=f'城市ID {city_id} 信息不存在！'
		)
	return db_city


@application.get('/get_cities', response_model=List[schemas.ReadCity], summary='查询多个城市信息')
async def get_cities(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
	"""
	执行数量，查询多个城市信息
	- **skip**: 起始查询位置
	- **limit**: 查询的数量
	- **db**: 依赖注入的数据库连接
	"""
	cities = crud.get_cities(db, skip, limit)
	return cities


@application.post('/create_city_data', response_model=schemas.ReadData, summary='创建城市疫情数据')
async def create_city_data(city_name: str, data: schemas.CreateData, db: Session = Depends(get_db)):
	"""
	创建城市疫情数据
	- **city_id**: 城市名称
	- **data**: 疫情数据
	- **db**: 依赖注入的数据库连接
	"""
	db_city = crud.get_city_by_name(db, city_name)
	if not db_city:
		raise HTTPException(
			status_code=status.HTTP_404_NOT_FOUND,
			detail=f'{city_name} 信息不存在！'
		)
	return crud.create_city_data(db, data, db_city.id)


@application.get('/get_data', response_model=List[schemas.ReadData], summary='查询城市疫情数据')
async def get_data(city_name: str = None, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
	"""
	查询城市疫情数据
	- **city_name**: 城市名称
	- **skip**: 查询的起始位置
	- **limit**: 查询数量
	- **db**: 依赖注入的数据库连接
	"""
	return crud.get_data(db, city_name, skip, limit)


@application.get('/')
def coronavirus(request: Request, city: str = None,
                skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
	data = crud.get_data(db, city, skip, limit)
	return templates.TemplateResponse('home.html', {
		'request': request,  # 这个数据是固定的
		'data': data,
		'sync_data_url': '/coronavirus/sync_coronavirus_data/jhu'
	})
